//
//  WJPDFFilesImportTool.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/27.
//

import UIKit

class WJPDFFilesImportTool: NSObject {
    // 处理PDF文件导入
    static func handlePDFImport(at url: URL) {
        do {
            let timeStamp = Int(Date().timeIntervalSince1970)
            // 由于文件可能来自沙盒外，需要先复制到应用沙盒内
            guard let directory = getDocumentsDirectory(timeStamp) else { return }
            let name = url.lastPathComponent
            let destinationURL = directory.appendingPathComponent(name)
            
            // 如果文件已存在，先删除
            if FileManager.default.fileExists(atPath: destinationURL.path) {
                try FileManager.default.removeItem(at: destinationURL)
            }
            
            // 复制文件到应用沙盒
            try FileManager.default.copyItem(at: url, to: destinationURL)
            
            let desiredSize = CGSize(width: 120, height: 160)

            WJPDFThumbnailGenerator.generate(from: destinationURL, thumbnailSize: desiredSize) { (thumbnail, fileSize) in
                let listModel = WJPDFListModel()
                listModel.imageData = thumbnail?.pngData()
                listModel.name = name
                listModel.suffix = "pdf"
                listModel.fileSize = fileSize ?? 0
                listModel.filePath = self.relativePath(timeStamp).appending("/\(url.lastPathComponent)")
                listModel.signState = false
                // 保存到数据库
                let id = try? listModel.save()
                listModel.id = id ?? 0
                
                NotificationCenter.default.post(name: .pdfListChangedNotification, object: listModel)
            }
        } catch {
            WJProgressHUD.showInfo(with: "Failed")
        }
    }
    
    static func getDocumentsDirectory(_ timeStamp: Int) -> URL? {

        guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        
        // 获取相对路径
        let relativePath = relativePath(timeStamp)
        let fullPath = documentsURL.appendingPathComponent(relativePath)
        
        do {
            try FileManager.default.createDirectory(at: fullPath, withIntermediateDirectories: true)
            return fullPath
        } catch {
            return nil
        }
    }

    static func relativePath(_ timeStamp: Int) -> String {
        return "PDF/Files/\(timeStamp)"
    }
}
